<script lang="ts" setup>
import { HomeDeatilType } from "@/typing";
import { useRouter } from "vue-router";
import 'vant/es/toast/style';
import { Toast } from "vant";
import { ref, toRefs, watch } from "vue";
import { storeToRefs } from "pinia";
import { localStoriesStore, userLocalStoriesStore } from "../../store";

const router = useRouter();

const localStore = localStoriesStore();
const { refreshHpCollectStore, selectHpCollectId } = localStore;

const userStore = userLocalStoriesStore();
const { isLogin } = storeToRefs(userStore);
const { getMyUserStatus } = userStore;

const props = defineProps<{
    listItem: HomeDeatilType
}>()

const { listItem } = toRefs(props)
isLogin.value = getMyUserStatus();
let toggleCollect = ref<boolean>(false);
let collect = ref<string>();
let isCollect = ref<boolean>();
isCollect.value = selectHpCollectId(listItem.value.id);

watch(() => isLogin.value, () => {
    isCollectShow(isLogin.value)
})

isCollectShow(isLogin.value)

function isCollectShow(isLogin:boolean) {
    if (!isLogin) {
        toggleCollect.value = false;
        collect.value = require("../../assets/card/bubble_collect.png");
    } else {
        if (isCollect.value) {
            toggleCollect.value = true;
            collect.value = require("../../assets/card/bubble_collected.png");
        }
    }
}

function updateCollect() {
    if (!isLogin.value) {
        router.push({
            name: 'login',
        })
    } else {
        if (toggleCollect.value) {
            toggleCollect.value = false;
            refreshHpCollectStore(listItem.value);
            collect.value = require("../../assets/card/bubble_collect.png");
            Toast('取消收藏');
        }
        else {
            toggleCollect.value = true;
            refreshHpCollectStore(listItem.value);
            collect.value = require("../../assets/card/bubble_collected.png");
            Toast('收藏成功');
        }
    }
}
</script>

<template>
    <div class="flex items-center">
        <img class="w-10 h-10" @click="updateCollect()"
            :src="collect || require('../../assets/card/bubble_collect.png')" alt="share">
    </div>
</template>